package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tooks.Constant;
import com.example.onlinemusic.tooks.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public ResponseBodyMessage<Boolean> login(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {
        User user = userMapper.selectByName(username);

        if (user == null) {
            System.out.println("登录失败!");
            return new ResponseBodyMessage<>(-1,"用户名或密码错误!", false);
        } else {
            boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
            if (!flg) {
                return new ResponseBodyMessage<>(-1,"密码错误! ", false);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, user);
            System.out.println("[login]: 用户" + username + " 登录成功! ");
            return new ResponseBodyMessage<>(0, "登录成功! ", true);
        }
    }
}
